﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Admin.Core.Middlewares/RequstResponseLogMilddware 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       RequstResponseLogMilddware
* 创建时间：  2025/5/23 18:53:02
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using SSPivot.Common.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace SSPivot.Admin.Core.Middlewares
{
    public class RequstResponseLogMilddware
    {
        /// <summary>
        ///
        /// </summary>
        private readonly RequestDelegate _next;
        private readonly IConfiguration _configuration;
        /// <summary>
        ///
        /// </summary>
        /// <param name="next"></param>
        public RequstResponseLogMilddware(RequestDelegate next, IConfiguration configuration)
        {
            _configuration = configuration;
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var isEnabled = _configuration.GetSection("AppSettings").GetValue<bool>("RequestResponseLogEnabled");
            if (isEnabled)
            {
                // 过滤，只有接口
                if (context.Request.Path.Value.Contains("api") || context.Request.Path.Value.Contains("Api"))
                {
                    context.Request.EnableBuffering();
                    Stream originalBody = context.Response.Body;
                    try
                    {
                        // 存储请求数据
                        await RequestDataLog(context);

                        using (var ms = new MemoryStream())
                        {
                            context.Response.Body = ms;

                            await _next(context);

                            // 存储响应数据
                            ResponseDataLog(context.Response, ms);

                            ms.Position = 0;
                            await ms.CopyToAsync(originalBody);
                        }
                    }
                    catch (Exception)
                    {
                        // 记录异常
                        //ErrorLogData(context.Response, ex);
                    }
                    finally
                    {
                        context.Response.Body = originalBody;
                    }
                }
                else
                {
                    await _next(context);
                }
            }
            else
            {
                await _next(context);
            }
        }

        private async Task RequestDataLog(HttpContext context)
        {
            var request = context.Request;
            var sr = new StreamReader(request.Body);

            var content = $" QueryData:{request.Path + request.QueryString}\r\n BodyData:{await sr.ReadToEndAsync()}";

            if (!string.IsNullOrEmpty(content))
            {
                Parallel.For(0, 1, e =>
                {
                    Serilog.Log.Error($"-------------------------\r\n Data:{DateTime.Now.ToString()}\r\nContent:{content}");
                });

                request.Body.Position = 0;
            }
        }

        private void ResponseDataLog(HttpResponse response, MemoryStream ms)
        {
            ms.Position = 0;
            var ResponseBody = new StreamReader(ms).ReadToEnd();
            // 去除 Html
            var reg = "<[^>]+>";
            var isHtml = Regex.IsMatch(ResponseBody, reg);
            if (!string.IsNullOrEmpty(ResponseBody))
            {
                Parallel.For(0, 1, e =>
                {
                    Serilog.Log.Error($"-------------------------\r\n Data:{DateTime.Now.ToString()}\r\nContent:{ResponseBody}");
                });
            }
        }
    }
}
